package com.sdp.irrigation.db.irrigation_location.service.impl;

import com.sdp.irrigation.entity.IrrigationLocation;
import com.sdp.right.utils.RightConstants;
import com.sdp.irrigation.db.irrigation_location.mapper.IrrigationLocationMapper;
import com.sdp.irrigation.db.irrigation_location.service.IIrrigationLocationService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * <p>
 * 国家地理信息 服务实现类
 * </p>
 *
 * @author zsp
 * @since 2024-12-14
 */
@Service
public class IrrigationLocationServiceImpl extends ServiceImpl<IrrigationLocationMapper, IrrigationLocation> implements IIrrigationLocationService {

	@Override
	public List<IrrigationLocation> queryLocationByLevel(String level) {
		LambdaQueryWrapper<IrrigationLocation> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(IrrigationLocation::getLocationLevel, level);
		lambdaQueryWrapper.orderByAsc(IrrigationLocation::getLocationNo);
		return list(lambdaQueryWrapper);
	}

	@Override
	public List<JSONObject> queryLocationTree() {
		List<JSONObject> treeList = new ArrayList<JSONObject>();
		List<IrrigationLocation> locationList = list();
		List<IrrigationLocation> rootList = new ArrayList<IrrigationLocation>();
		
		if(locationList!=null && locationList.size()>0) {
			for(IrrigationLocation l : locationList) {
				if(StringUtils.isEmpty(l.getLocationParentNo()) || RightConstants.否.getCode().equals(l.getLocationParentNo())) {
					rootList.add(l);
					
				}
			}
		}
		
		if(rootList!=null && rootList.size()>0) {
			
			for(int i=0;i<rootList.size();i++) {
				JSONObject parentObj = new JSONObject();
				parentObj.put("title", rootList.get(i).getLocationName());
				parentObj.put("value", rootList.get(i).getLocationNo());
				treeList.add(parentObj);
				getChildTreeSelect(parentObj, locationList);
			}
		}
		
		return treeList;
	}
	
	@SuppressWarnings({ "unchecked" })
	private void getChildTreeSelect(JSONObject parentObj,List<IrrigationLocation> locationList) {
		List<Object> childList = new ArrayList<Object>();
	
		for(int j=0;j<locationList.size();j++) {
			if(!StringUtils.isEmpty(locationList.get(j).getLocationNo()) && parentObj.getString("value").equals(locationList.get(j).getLocationParentNo())) {
				
				if(parentObj.get("children")==null) {
					parentObj.put("children", childList);
				}else {
					childList = (List<Object>) parentObj.get("children");
				}
				
				JSONObject childObj = new JSONObject();
				childObj.put("title", locationList.get(j).getLocationName());
				childObj.put("value", locationList.get(j).getLocationNo());
				childList.add(childObj);
				getChildTreeSelect(childObj, locationList);
			}
			
		}
	}

}
